<?php

class TrackingController extends Controller
{
	public function actionIndex()
	{
        $this->pageTitle = Yii::t('app', 'Tracking for task');
        $model = new Tracking();

        $this->render('index', array(
            'model' => $model,
        ));
	}

    public function actionView($id = null) {
        $this->pageTitle = Yii::t('app', 'Tracking for task');
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('tracking/index'));
        }

        $model = Tracking::model()->findByPk($id, 'del_flg = 0');
        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(array('tracking/index'));
        }

        //update status for task
        if (isset($_POST['Tracking']) && $data = $_POST['Tracking']) {
            $model->attributes = $data;
            if ($model->save()) {
                Yii::app()->user->setFlash('success', Yii::t('app', 'Status updated success!'));
                $this->redirect(array('tracking/index'));
            }else{
                Yii::app()->user->setFlash('error', Yii::t('app', 'Status update false!'));
            }
        }

        // get all data view Task
        $lisClient = Client::getListClient();
        $listTransporter = TransporterDetail::getListTransporter();
        $data = array();
        $data['id_client'] = $lisClient[$model->id_client];
        $data['id_tpdetail'] = $listTransporter[$model->id_tpdetail];
        $data['ship_date'] = $model->ship_date;
        $data['id_by_matter'] = TrackingTask::getListMatterTask($model->id_tracking);
        $data['signature_transporter'] = CHtml::image(Yii::app()->getBaseUrl().'/signature/'.$model->id_tracking.'.png');

        $this->render('view', array(
            'model' => $model,
            'data' => $data,
        ));
    }

    public function actionAdd(){
        $this->pageTitle = Yii::t('app', 'Ship task to client');

        $model = new Tracking();
        if (isset($_POST['Tracking']) && $data = $_POST['Tracking']) {
//            $dataTask = $_POST['id_matter_task'];
            $transaction = Yii::app()->db->beginTransaction();
            try {
                $errors = array();
                $errorMessages = '';
                $model->attributes = $data;
                if (!$model->save()) {
                    $errors[] = $model->getErrors();
                }else{
                    if(isset($_POST['id_matter_task']) && $_POST['id_matter_task']){
                        $dataTask = $_POST['id_matter_task'];
                        foreach($dataTask as $data){
                            $modelTask = Task::model()->findByPk($data, 'del_flg = 0 AND status =' . Constant::STATUS_CLOSE);
                            if($modelTask){
                                $modelTrackTask = new TrackingTask();
                                $modelTrackTask->id_tracking = $model->id_tracking;
                                $modelTrackTask->id_task = $data;
                                $modelTrackTask->id_by_matter = $modelTask->id_by_matter;
                                if (!$modelTrackTask->save()) {
                                    $errors[] = $model->getErrors();
                                }
                            }
                        }
                    }else{
                        $errorMessages .= Yii::t('app', 'Please choose Task ID!').'<br>';
                    }
                }
                //Process error message
                if ($errors) {
                    foreach ($errors as $k => $v) {
                        foreach ($v as $f) {
                            foreach ($f as $id => $m) {
                                $errorMessages .= $m.'<br>';
                            }
                        }
                    }
                }

                if (!empty($errorMessages)) throw new Exception();

                //generate signature
                $data_signature = $_POST['data_signature'];
                $option = array(
                    'file_name' => $model->id_tracking,
                    'drawMultiplier'=> 1
                );
                if($data_signature)
                    Common::sigJsonToImage($data_signature, $option);

                $transaction->commit();

                Yii::app()->user->setFlash('success', Yii::t('app', 'Tracking created success!'));
                $this->redirect(array('tracking/index'));

            } catch (Exception $e) {
                $transaction->rollback();
                Yii::app()->user->setFlash('error', "$errorMessages");
            }
        }

        $this->render('add', array(
            'model' => $model,
            'listClient' => Client::getListClient(),
            'listTrensporter' => TransporterDetail::getListTransporter(),
        ));
    }

    public function actionUpdate($id = null) {
        $this->pageTitle = Yii::t('app', 'Ship task to client');
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('tracking/index'));
        }

        $model = Tracking::model()->findByPk($id, 'del_flg = 0');
        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(array('tracking/index'));
        }

        if (isset($_POST['Tracking']) && $data = $_POST['Tracking']) {
            $transaction = Yii::app()->db->beginTransaction();
            try {
                $errors = array();
                $errorMessages = '';
                $model->attributes = $data;
                if (!$model->save()) {
                    $errors[] = $model->getErrors();
                }else{
                    if(isset($_POST['id_matter_task']) && $_POST['id_matter_task']){
                        $dataTask = $_POST['id_matter_task'];
                        foreach($dataTask as $data){
                            $modelTask = Task::model()->findByPk($data, 'del_flg = 0 AND status =' . Constant::STATUS_CLOSE);
                            $criteria = new CDbCriteria();
                            $criteria->addCondition('id_tracking = :id_tracking');
                            $criteria->addCondition('id_task = :id_task');
                            $criteria->params = array(':id_tracking'=>$id, ':id_task'=>$data);
                            $countTrackTask = TrackingTask::model()->count($criteria);
                            if($modelTask && $countTrackTask<1){
                                $modelTrackTask = new TrackingTask();
                                $modelTrackTask->id_tracking = $model->id_tracking;
                                $modelTrackTask->id_task = $data;
                                $modelTrackTask->id_by_matter = $modelTask->id_by_matter;
                                if (!$modelTrackTask->save()) {
                                    $errors[] = $model->getErrors();
                                }
                            }
                        }
                    }else{
                        $errorMessages .= Yii::t('app', 'Please choose Task ID!').'<br>';
                    }
                }
                //Process error message
                if ($errors) {
                    foreach ($errors as $k => $v) {
                        foreach ($v as $f) {
                            foreach ($f as $id => $m) {
                                $errorMessages .= $m.'<br>';
                            }
                        }
                    }
                }

                if (!empty($errorMessages)) throw new Exception();
                $transaction->commit();

                Yii::app()->user->setFlash('success', Yii::t('app', 'Tracking created success!'));
                $this->redirect(array('tracking/index'));

            } catch (Exception $e) {
                $transaction->rollback();
                Yii::app()->user->setFlash('error', "$errorMessages");
            }
        }
        $this->render('update', array(
            'model' => $model,
            'listClient' => Client::getListClient(),
            'listTrensporter' => TransporterDetail::getListTransporter(),
            'listTrackingTask' => TrackingTask::getListMatterTask($id, true),
        ));
    }

    public function actionDelete($id = null) {
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('tracking/index'));
        }

        $model = Tracking::model()->findByPk($id, 'del_flg = 0');
        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(array('tracking/index'));
        }

        $model->del_flg = 1;
        if ($model->save(false)) {
            if(!isset($_GET['ajax'])){
                Yii::app()->user->setFlash('success', Yii::t('app', 'Tracking - Deleted Successfully'));
                $this->redirect(array('tracking/index'));
            }
            else{
                echo '<div class="alert alert-success fade in"><button type="button" class="close" data-dismiss="alert">×</button>'.Yii::t('app', 'Tracking - Deleted Successfully').'</div>';
                die();
            }

        }

    }

    public function actionfilterTaskByClient(){
        if(isset($_POST['id_client'])&& $idClient = $_POST['id_client']){
            $criteria = new CDbCriteria();
            $criteria->with = 'track';
            $criteria->addInCondition('track.status', array(Constant::STATUS_SHIP_PENDING, Constant::STATUS_SHIP_SHIPED));
            $criteria->addCondition('track.id_client = :id_client');
            $criteria->addCondition('track.del_flg = 0');
            $criteria->params[':id_client'] = $idClient;
            $modelTrackTask = TrackingTask::model()->findAll($criteria);
            $taskTrackArr = array();
            if($modelTrackTask){
                foreach($modelTrackTask as $trackTask){
                    $taskTrackArr[] = $trackTask->id_task;
                }
            }

            $listTaskByClient = Task::_getTaskByClient($idClient);
            $_htmlOptionSelect = '';
            if($listTaskByClient){
                foreach($listTaskByClient as $task){
                    if(!in_array($task->id_task, $taskTrackArr))
                        $_htmlOptionSelect .= '<option value="'.$task->id_task.'">'.$task->id_by_matter.'</option>';
                }
            }
            die($_htmlOptionSelect);
        }
    }

    public function actionGenerateSignature(){
        $result = array();
        if(isset($_POST['data']) && isset($_POST['id_transporter'])){
            $data = $_POST['data'];
            if(empty($data)){
                $result['hasError']=1;
                $result['ErrorMessage']='<div class="alert alert-error fade in"><button type="button" class="close" data-dismiss="alert">×</button>'.Yii::t('app', 'Please add signarute!').'</div>';
            }else{
                $option = array(
                    'file_name' => $_POST['id_transporter'],
                    'imageSize' => array(Constant::IMG_WIDTH_SIGNATURE, Constant::IMG_HEIGHT_SIGNATURE),
                    'bgColour' => array(0xff, 0xff, 0xff),
                    'penWidth' => 2,
                    'penColour' => array(0x14, 0x53, 0x94),
                    'drawMultiplier'=> 1
                );
                $srcImage = Common::sigJsonToImage($data, $option);
                $result['hasError']=0;
                $result['result']=CHtml::image(Yii::app()->getBaseUrl().DIRECTORY_SEPARATOR.$srcImage);
            }

            die(json_encode($result));
        }
    }

    public function actionfillSignatureByTransporter(){
//        Common::debugdie(Yii::app()->basePath);
        if(isset($_POST['id_transporter'])){
            $data = $_POST['id_transporter'];
            $fileSignaturePath = Yii::app()->basePath.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'signature'.DIRECTORY_SEPARATOR.$data.'.png';
            if(file_exists($fileSignaturePath)){
                die(CHtml::image(Yii::app()->getBaseUrl().'/signature/'.$data.'.png'));
            }
        }
        die();
    }

}